#include "GraphicEngine.h"

bool GraphicEngine::createWindow( int width, int height, int depth )
{
    m_width = width;
    m_height = height;
    m_depth = depth;

    if( ! initSDL() )
    {
        exitEngine();
        return false;
    }
    if( ! initGL() )
    {
        return false;
    }

    return true;
}

void GraphicEngine::clearBackBuffer( void )
{

}

void GraphicEngine::swapBuffers( void )
{

}

void GraphicEngine::exitEngine( void )
{
    //TODO: Ajouter le free surface du sceen
    SDL_Quit();
}

bool GraphicEngine::initSDL( void )
{
   /* Flags to pass to SDL_SetVideoMode */
    int videoFlags;

    /* this holds some info about our display */
    const SDL_VideoInfo *videoInfo;

    /* initialize SDL */
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
	{
	    fprintf( stderr, "Video initialization failed: %s\n", SDL_GetError( ) );
	    return false;
	}

    /* Fetch the video info */
    videoInfo = SDL_GetVideoInfo( );

    if ( !videoInfo )
	{
	    fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) );
	    return false;
	}

    /* the flags to pass to SDL_SetVideoMode */
    videoFlags  = SDL_OPENGL;          /* Enable OpenGL in SDL */
    videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */

    /* This checks to see if surfaces can be stored in memory */
    if ( videoInfo->hw_available )
    {
        videoFlags |= SDL_HWSURFACE;
        cout << "Surface type : Hardware" << endl;
    }
    else
	{
	    videoFlags |= SDL_SWSURFACE;
	    cout << "Surface type : Software" << endl;
	}
    /* This checks if hardware blits can be done */
    if ( videoInfo->blit_hw )
    {
        videoFlags |= SDL_HWACCEL;
        cout << "Hardware acceleration = true" << endl;
    }
    else
    {
        cout << "Hardware acceleration = false" << endl;
    }

    /* Sets up OpenGL double buffering */
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

    /* get a SDL surface */
    m_screen = SDL_SetVideoMode( m_width, m_height, m_depth,videoFlags );

    /* Verify there is a surface */
    if ( !m_screen )
	{
	    fprintf( stderr,  "Video mode set failed: %s\n", SDL_GetError( ) );
	    return false;
	}

	return true;
}

bool GraphicEngine::initGL( void )
{
    // Enable smooth shading
    glShadeModel( GL_SMOOTH );

    // Set the background black
    glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );

    // Depth buffer setup
    glClearDepth( 1.0f );

    // Enables depth testing
    glEnable( GL_DEPTH_TEST );

    // Enables 2D texturing
    glEnable( GL_TEXTURE_2D );

    // The type of depth test to do
    glDepthFunc( GL_LEQUAL );

    // Really Nice Perspective Calculations
    glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );

    return true;
}
